package com.mszlu.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mszlu.blog.dao.dos.Archives;
import com.mszlu.blog.dao.mapper.ArticleBodyMapper;
import com.mszlu.blog.dao.mapper.ArticleMapper;
import com.mszlu.blog.dao.mapper.ArticleTagMapper;
import com.mszlu.blog.dao.pojo.Article;
import com.mszlu.blog.dao.pojo.ArticleBody;
import com.mszlu.blog.dao.pojo.ArticleTag;
import com.mszlu.blog.dao.pojo.SysUser;
import com.mszlu.blog.service.*;
import com.mszlu.blog.utils.UserThreadLocal;
import com.mszlu.blog.vo.ArticleBodyVo;
import com.mszlu.blog.vo.ArticleVo;
import com.mszlu.blog.vo.Result;
import com.mszlu.blog.vo.TagVo;
import com.mszlu.blog.vo.params.ArticleParam;
import com.mszlu.blog.vo.params.PageParams;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private TagService tagService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private ArticleTagMapper articleTagMapper;
    @Resource
    private ArticleBodyMapper articleBodyMapper;
    @Resource
    private CategoryService categoryService;
    @Resource
    private ThreadService threadService;

    /**
     * 使用自定义查询
     * @param pageParams    分页参数
     * @return listArticle
     */
    @Override
    public Result listArticle(PageParams pageParams) {
        //创建分页对象
        Page<Article> page = new Page<>(pageParams.getPage(),pageParams.getPageSize());
        //分页泛型 查询
        IPage<Article> articleIPage = articleMapper.listArticle(
                page,
                //分类id
                pageParams.getCategoryId(),
                //标签id
                pageParams.getTagId(),
                //年
                pageParams.getYear(),
                //月
                pageParams.getMonth());
        //获取分页结果集
        List<Article> records = articleIPage.getRecords();

        return Result.success(copyList(records,true,true));
    }

//    @Override
//    public Result listArticle(PageParams pageParams) {
//
//         // 1. 分页查询 article数据库表
//        Page<Article> page = new Page<>(pageParams.getPage(),pageParams.getPageSize());
//        //创建lambda查询条件
//        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
//        //当分类id不为null时 增加筛选条件
//        if (pageParams.getCategoryId() != null){
//            // and category_id=#{categoryId}
//            queryWrapper.eq(Article::getCategoryId,pageParams.getCategoryId());
//        }
//
//        List<Long> articleIdList = new ArrayList<>();
//        //增加标签分类显示
//        if (pageParams.getTagId() != null){
//            //加入标签 条件查询
//            //article表中 并没有tag字段 一篇文章 有多个标签
//            //article_tag  article_id 1 : n tag_id
//            //一对多查询
//            LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            articleTagLambdaQueryWrapper.eq(ArticleTag::getTagId,pageParams.getTagId());
//
//            List<ArticleTag> articleTags = articleTagMapper.selectList(articleTagLambdaQueryWrapper);
//
//            for (ArticleTag articleTag : articleTags) {
//                //将查询出来对的文章列表加入到文章id集合中
//                articleIdList.add(articleTag.getArticleId());
//            }
//            if (articleIdList.size() > 0){
//                // and id in(1,2,3) 有值则作为查询判断条件
//                //in 列表查询
//                queryWrapper.in(Article::getId,articleIdList);
//            }
//        }
//        //是否置顶进行排序
//        //order by create_date desc 权重和创建时间排序
//        queryWrapper.orderByDesc(Article::getWeight,Article::getCreateDate);
//        //
//        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
//        //
//        List<Article> records = articlePage.getRecords();
//        //能直接返回吗？ 很明显不能
//        List<ArticleVo> articleVoList = copyList(records,true,true);
//        return Result.success(articleVoList);
//    }



    /**
     * 获取最热文章信息
     * @param limit 显示条数
     * @return 文章结果集
     * @Author linKe
     * @Date 2021/12/5 11:22
     */
    @Override
    public Result hotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getViewCounts).
      select(Article::getId,Article::getTitle)
        .last("limit "+limit);
        //select id,title from article order by view_counts desc limit 5
        List<Article> articles = articleMapper.selectList(queryWrapper);
        //文章结果复制
        return Result.success(copyList(articles,false,false));
    }



    /**
     * 获取最新文章信息
     * @param limit 显示条数
     * @return 文章结果集
     * @Author linKe
     * @Date 2021/12/5 11:22
     */
    @Override
    public Result newArticles(int limit) {
        //创建lambda表达式查询
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //设置降序 根据创建时间
        queryWrapper.orderByDesc(Article::getCreateDate)
         //查询所显示内容
       .select(Article::getId,Article::getTitle)
        //无视优化规则直接拼接到 sql 的最后(有sql注入的风险,请谨慎使用)  拼接显示条数
        .last("limit "+limit);
        //select id,title from article order by create_date desc desc limit 5
        List<Article> articles = articleMapper.selectList(queryWrapper);

        return Result.success(copyList(articles,false,false));
    }



    @Override
    public Result listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();
        return Result.success(archivesList);
    }


    /**
     * 使用线程池增加阅读数
     *
     * 1. 根据id查询 文章信息
     * 2. 根据bodyId和categoryId 去做关联查询
     */
    @Override
    public Result findArticleById(Long articleId) {
        //查询文章
        Article article = this.articleMapper.selectById(articleId);
        ArticleVo articleVo = copy(article, true, true,true,true);
        //查看完文章了，新增阅读数，有没有问题呢？
        //查看完文章之后，本应该直接返回数据了，这时候做了一个更新操作，更新时加写锁，阻塞其他的读操作，性能就会比较低
        // 更新 增加了此次接口的 耗时
        // 如果一旦更新出问题，不能影响 查看文章的操作
        //线程池  可以把更新操作 扔到线程池中去执行，和主线程就不相关了 异步线程操作
        threadService.updateArticleViewCount(articleMapper,article);
        //影响主线程显示   只能重新进入
        return Result.success(articleVo);
    }


    /**
     * 1. 发布文章 目的 构建Article对象
     * 2. 作者id  当前的登录用户
     * 3. 标签  要将标签加入到 关联列表当中
     * 4. body 内容存储 article bodyId
     */
    @Override
    public Result publish(ArticleParam articleParam) {
        //此接口 要加入到登录拦截当中
        SysUser sysUser = UserThreadLocal.get();
        //
        Article article = new Article();
        //
        article.setAuthorId(sysUser.getId());
        //设置权重  默认是0
        article.setWeight(Article.Article_Common);
        article.setViewCounts(0);
        article.setTitle(articleParam.getTitle());
        article.setSummary(articleParam.getSummary());
        article.setCommentCounts(0);
        article.setCreateDate(System.currentTimeMillis());
        article.setCategoryId(Long.parseLong(articleParam.getCategory().getId()));
        //插入之后 会生成一个文章id
        this.articleMapper.insert(article);
        //tag 获取标签集
        List<TagVo> tags = articleParam.getTags();
        if (tags != null){
            for (TagVo tag : tags) {
                //
                Long articleId = article.getId();
                //
                ArticleTag articleTag = new ArticleTag();
                articleTag.setTagId(Long.parseLong(tag.getId()));
                articleTag.setArticleId(articleId);
                //保存articleTag
                articleTagMapper.insert(articleTag);
            }
        }
        //body
        ArticleBody articleBody  = new ArticleBody();
        articleBody.setArticleId(article.getId());
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        //articleBody 存储
        articleBodyMapper.insert(articleBody);

        //设置内容id
        article.setBodyId(articleBody.getId());
        //更新表
        articleMapper.updateById(article);
        Map<String,String> map = new HashMap<>();
        //转string  防止精度损失
        map.put("id",article.getId().toString());
        return Result.success(map);
    }





    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record,isTag,isAuthor,false,false));
        }
        return articleVoList;
    }


    /**
     * 方法重载
     * @param records 结果集
     * @param isTag 标签信息
     * @param isAuthor 作者信息
     * @param isBody 结果集
     * @param isCategory 分类信息
     * @return articleVoList
     * @Author linKe
     * @Date 2021/12/5 10:27
     */

    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor, boolean isBody,boolean isCategory) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record,isTag,isAuthor,isBody,isCategory));
        }
        return articleVoList;
    }

    /**
     * BeanUtils 属性转移 实现条件按需查询
     * @param article 文章
     * @param isTag 文章标签
     * @param isAuthor  文章作者
     * @param isBody    文章内容
     * @param isCategory  文章分类
     * @Author linKe
     * @Date 2021/12/5 0:26
     * @return  articleVo   根据条件判断所返回的内容
     */

    private ArticleVo copy(Article article, boolean isTag, boolean isAuthor, boolean isBody,boolean isCategory){
        ArticleVo articleVo = new ArticleVo();
        //设置vo对象id
        articleVo.setId(String.valueOf(article.getId()));
        //属性转移
        BeanUtils.copyProperties(article,articleVo);
        //设置copy 创建时间   时间格式
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));

        //并不是所有的接口 都需要标签 ，作者信息  按需查询
        if (isTag){
            //根据文章id 查询标签信息
            Long articleId = article.getId();
            articleVo.setTags(tagService.findTagsByArticleId(articleId));
        }
        if (isAuthor){
            //查询作者信息 的名字
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(sysUserService.findUserById(authorId).getNickname());
        }
        if (isBody){
            //查询文章内容
            Long bodyId = article.getBodyId();
            articleVo.setBody(findArticleBodyById(bodyId));
        }
        if (isCategory){
            //查询文章分类
            Long categoryId = article.getCategoryId();
            articleVo.setCategory(categoryService.findCategoryById(categoryId));
        }
        return articleVo;
    }



    private ArticleBodyVo findArticleBodyById(Long bodyId) {
        //查询文章内容
        ArticleBody articleBody = articleBodyMapper.selectById(bodyId);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }

}
